<template>
	<view class="shangc-box">
		<view class="shangc-neir" v-for="(item,index) in arrcont" :key="index">
			<label :for="item.id">
				{{item.name}}
			</label>
			<input type="text" :id="item.id" :type="item.type" :placeholder="'请输入'  + item.name" v-model="item.text"
				name="">
			<view class="" v-show="item.fuz" @click="fuz(item)">
				复制
			</view>
			<view class="" v-show="item.yuan">
				{{item.hou}}
			</view>
		</view>


		<view class="shangc-neir" v-for="(item,index) in changSuk" :key="index">
			<label :for="item.id">
				{{item.name}}
			</label>
			<input type="text" v-model="item.text" :id="item.id" :type="item.type" placeholder="请输入仓库索引" />
			<view class="circle-btn" v-if="index == 0" @click="tianjiaadd(index)">
				+
			</view>
			<view class="circle-btn" v-else  @click="delect(index)">
				—
			</view>
		</view>
		
	
		  
	



		<!-- <view class="shangc-neir">
			<picker mode="selector" :range="options" :value="selectedIndex" @change="onSelectorChange">
				<view class="picker">
					<view class="">
						仓库：
					</view>
					<view class="juzhong">
						{{ options[selectedIndex] }}
					</view>
				</view>
			</picker>
		</view> -->



		<view class="shangc-neir" @click="showType">
			<view>分类</view>
			<picker style="flex: 1;text-align: center;" mode="multiSelector" :range="pickerRange" :value="pickerValue"
				@change="unpType" @cancel="onCancel" @columnchange='onChange'>
				<view class="">
					{{selectedMain}}
				</view>
			</picker>
		</view>


		<view class="imgasea">
			<l-upload uploadType='img' @complete="complete" @remove="remove" ref="childRef"></l-upload>
		</view>
		
		
		<view class="unpdata" style="width: 200rpx;">
			图
		</view>
		
		
		<view class="imgasea">
			<l-upload uploadType='img' @complete="completea" @remove="remove" ref="childRefa"></l-upload>
		</view>
		
		<view class="unpdata" @click="unpdflin">
			修改商品
		</view>
	</view>
</template>

<script>
	import api from '../../api/Channel.js'
	import commonMixin from '@/mixins/qiLiuyun.js';
	import request from '../../api/index.js'
	import suffixAddress from '../../api/suffixAddress.js'
	export default {
		mixins: [commonMixin],
		data() {
			return {
				arrcont: [{
						name: '名称',
						text: '',
						type: 'text',
						hou: '',
						id: 0,
						fuz: true

					},
					{
						name: '价格',
						text: null,
						type: 'digit',
						hou: '元',
						id: 1,
						fuz: false,
						yuan: true
					},

					{
						name: '扣眼',
						text: null,
						type: 'text',
						hou: '元',
						id: 3,
						fuz: false
					},
					{
						name: '大小',
						text: null,
						type: 'text',
						hou: '',
						id: 4,
						fuz: false
					},
					{
						name: '简介',
						text: null,
						type: 'text',
						hou: '',
						id: 5,
						fuz: false
					},
					
				],
				arrimgas: [],
				qiniuyunImage: [],
				showPicker: true, // 控制picker显示隐藏
				pickerValue: [0, 0], // 当前选中索引 [主分类索引, 子分类索引]
				categories: [],
				pickerRange: [
					[],
					[]
				], // picker需要的二维数组 [[主分类数组], [子分类数组]]
				selectedMain: '请选择分类',
				selectedSub: '',
				commodities: [],
				categoryId: null,
				options: ['柜台', '仓库 ', '虎门'],
				selectedIndex: 0,
				shangcTUe: false,
				changSuk: [],
				shangpId:'',
				aiImageKeys:[],
				aiImagesunp:[]
			};
		},
		onLoad(options) {
			const objectStr = decodeURIComponent(options.data);
			const parsedObject = JSON.parse(objectStr);
			this.xiugaia(parsedObject)
			this.acategories()
		},
		methods: {
			tianjiaadd() {
				this.changSuk.push({
					name: '仓库索引',
					text: ''
				})
			},
			delect(index){
				this.changSuk.splice(index, 1);
			},
			async xiugaia(options) {
				let obj = {
					url: api.ctrl + suffixAddress.add().type + '/' + options
				}
				let res = await request(obj)
				let text = res.data
			
				this.$refs.childRef.xiugaitpi(text);
				this.$refs.childRefa.xiugaitpia(text);
				this.arrcont.forEach(el => {
					if (el.id == 0) {
						el.text = text.name
					} else if (el.id == 1) {
						el.text = text.salePrice
					} else if (el.id == 3) {
						el.text = text.eyeletType
					} else if (el.id == 4) {
						el.text = text.size
					}
				})
				
				if(text.sourceIndex.length == 0){
					this.changSuk.push({
						name: '仓库索引',
						text: ''
					})
				}
				text.sourceIndex.forEach(el=>{
					this.changSuk.push({
						name: '仓库索引',
						text: el
					})
				})
				this.selectedMain = text.categoryName
				this.categoryId = text.categoryId
				this.shangpId = text.id
			},
			unpType(e) {
				let th = this
				const mainIndex = e.detail.value[0];
				const subIndex = e.detail.value[1];
				const mainName = this.pickerRange[0][mainIndex];
				const subName = this.pickerRange[1][subIndex];
				this.selectedMain = mainName;
				this.selectedSub = subName;
				if (subName == undefined) {
					this.selectedMain = mainName
				}
				this.selectedMain = subName
				this.commodities.forEach((elenent, index) => {
					if (elenent.name == mainName) {
						elenent.children.forEach((elen, index) => {
							if (elen.name == subName) {
								th.categoryId = elen.id
							}
						})
						if (elenent.children.length == 0) {
							th.categoryId = elenent.id
							th.selectedMain = elenent.name
						}
					}
				})
				console.log(th.categoryId)
				// console.log('选中的主分类:', mainName);
				// console.log('选中的子分类:', subName);
			},
			showType(e) {
				this.showPicker = true
			},
			onChange(e) {
				const column = e.detail.column;
				const value = e.detail.value;

				// 如果是第一列变动（主分类）
				if (column === 0) {
					const mainIndex = value;

					// 更新二级分类数据
					const subCategories = this.commodities[mainIndex]?.children.map(child => child.name) || [];

					// 更新 pickerRange 第二列
					this.pickerRange[1] = subCategories;

					// 重设 pickerValue（保持第一列当前值，第二列归0）
					this.pickerValue = [mainIndex, 0];
				} else {
					// 如果是第二列变动，仅更新 pickerValue
					this.pickerValue[1] = value;
				}
			},
			onCancel(e) {
				this.showPicker = false;
				console.log('取消选择了分类');
			},
			async acategories() {
				let obj = {
					url: api.ctrl + suffixAddress.add().commodities,
				}
				let res = await request(obj)
				this.commodities = res.data // 假设你的数据在 res.data

				// 提取一级分类名
				const mainCategories = this.commodities.map(item => item.name)
				// 提取第一个一级分类的子分类名
				const subCategories = this.commodities[0]?.children.map(child => child.name) || []

				this.pickerRange = [mainCategories, subCategories]
			},
			remove(e) {
				// console.log(e)
				// this.qiniuyunImage.splice(e.index, 1);
				// console.log(this.qiniuyunImage)
			},
			async complete(e) {
				this.arrimgas = e.imageArr
			},
			async completea(e) {
				this.aiImageKeys = e.imageArr
			},
			async unpdflin() {
				let th = this;
				if (this.shangcTUe) {
					return
				}
				if (this.arrimgas.length == 0) {
					uni.showToast({
						title: '请上传图片',
						icon: 'error', // 可选值：success、loading、none
						duration: 1000 // 显示时长（单位：ms）
					});
					return
				} else if (th.arrcont[0].text == '') {
					uni.showToast({
						title: '请输入商品名字',
						icon: 'error', // 可选值：success、loading、none
						duration: 1000 // 显示时长（单位：ms）
					});
					return
				} else if (th.arrcont[1].text == '') {
					uni.showToast({
						title: '请输入价格',
						icon: 'error', // 可选值：success、loading、none
						duration: 1000 // 显示时长（单位：ms）
					});
					return
				} else if (th.categoryId == null) {
					uni.showToast({
						title: '请输入分类',
						icon: 'error', // 可选值：success、loading、none
						duration: 1000 // 显示时长（单位：ms）
					});
					return
				}

				this.shangcTUe = true
				uni.showLoading({
					title: '上传中...'
				});


				// 同时发起所有上传请求，并在所有完成后同步处理结果
				// 如果发现 filePath 总是同一个，建议使用传统 for 循环，确保每次迭代都获取正确的路径
				this.qiniuyunImage = [];
				for (const filePath of this.arrimgas) {
					if(filePath.key){
						this.qiniuyunImage.push(filePath.key)
					}else{
						// 等待上一张上传完成才继续下一张
						let key = await this.Tokenqiniu(filePath.url)
						console.log('上传文件路径：', filePath)
						console.log('返回的 key：', key)
						this.qiniuyunImage.push(key)
					}
					
				}
				
				this.aiImagesunp = [];
				for (const filePath of this.aiImageKeys) {
					if(filePath.key){
						this.aiImagesunp.push(filePath.key)
					}else{
						// 等待上一张上传完成才继续下一张
						let key = await this.Tokenqiniu(filePath.url,'ai-generate-res')
						console.log('上传文件路径：', filePath)
						console.log('返回的 key：', key)
						this.aiImagesunp.push(key)
					}
					
				}
				this.UploadProducts()
			},
			async UploadProducts() {
				let th = this
				let source = '';
				if (th.options[th.selectedIndex] == '柜台') {
					source = 1
				} else if (th.options[th.selectedIndex] == '仓库') {
					source = 2
				} else if (th.options[th.selectedIndex] == '虎门') {
					source = 3
				}

				let arrSuk = []

				this.changSuk.forEach(el=>{
					if(el.text == ''){
						
					}else{
						arrSuk.push(el.text)
					}
				}) 
				
				let obj = {
					data: {
						"id":th.shangpId,
						"name": th.arrcont[0].text,
						"desc":th.arrcont[4].text,
						"coverList": th.qiniuyunImage,
						"categoryId": th.categoryId,
						"salePrice": th.arrcont[1].text,
						"source": source,
						"sourceIndex": arrSuk,
						"size": th.arrcont[3].text,
						"eyeletType": th.arrcont[2].text,
						"aiImageKeys": this.aiImagesunp
					},
					url: api.ctrl + '/commodities',
					method: "put",
				}
				console.log(obj)
				let res = await request(obj)
				uni.hideLoading()
				uni.showToast({
					title: '修改成功',
					icon: 'success', // 可选值：success、loading、none
					duration: 1000 ,// 显示时长（单位：ms）
					
				});
				uni.redirectTo({
					url: '/pages/jiemxiajia/jiemxiajia?data=' + encodeURIComponent(JSON.stringify({id:this.shangpId}))
				});
			},
			onSelectorChange(e) {
				this.selectedIndex = e.detail.value
			},
			fuz(itme) {
				console.log(itme)
				if (itme.text == '' || itme.text == null) {
					uni.showToast({
						title: '不能复制空的',
						icon: 'error'
					});
					return
				}
				uni.setClipboardData({
					data: itme.text,
					success() {
						uni.showToast({
							title: '复制成功',
							icon: 'success'
						});
					}
				})

			}
		}
	}
</script>

<style lang="less">
	
	.shangc-box {
		background-color: #F5F5F5;
		padding-top: 40upx;
	}

	.shangc-neir {
		background-color: #fff;
		padding: 40upx;
		box-sizing: border-box;
		display: flex;
		width: 100vw;
		border-bottom: 1px solid #F5F5F5;

		>input {
			flex: 1;
			text-align: center;
		}
	}

	.imgasea {
		padding-left: 25rpx;
	}

	.unpdata {
		box-sizing: border-box;
		padding: 20rpx;
		margin: 20rpx;
		text-align: center;
		background: #FF9900;
		border-radius: 20rpx;
		font-size: 40rpx;
		// color: #F5F5F5;
	}

	.picker {
		display: flex;
	}

	.juzhong {
		width: 500rpx;
		text-align: center;
	}

	.shangc-neir {
		display: flex;
		align-items: center;
		/* 垂直居中 */
		justify-content: flex-start;
		/* 横向排列 */
	}

	input {
		height: 100rpx;
	}

	label {
		margin-right: 10px;
		font-size: 16px;
	}



	.circle-btn {
		width: 40px;
		height: 40px;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #ff6600;
		color: white;
		font-size: 24px;
		border-radius: 50%;
		/* 圆形 */
		cursor: pointer;
		margin-left: 10px;
		transition: background-color 0.3s ease;
	}

	.circle-btn:hover {
		background-color: #e65c00;
		/* 鼠标悬停时的背景颜色 */
	}
</style>